package com.hsogoo.avatar.demo;

import com.google.gson.Gson;
import com.hsogoo.avatar.demo.handler.DemoClientHandler;
import com.hsogoo.avatar.model.AvatarRequest;
import com.hsogoo.avatar.model.AvatarResponse;
import com.hsogoo.avatar.transport.AvatarFuture;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author huangsaigang
 * Created @2018/10/1.
 */
public class DemoConnector {

    private final static int port = 8888;
    private final static String host = "localhost";
    private final static Bootstrap b = new Bootstrap();
    private final static EventLoopGroup workerGroup = new NioEventLoopGroup();
    private static ChannelFuture f = null;

    static  {
        b.group(workerGroup); // (2)
        b.channel(NioSocketChannel.class); // (3)
        b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new DemoClientHandler());
                ch.pipeline().addLast(new StringEncoder());
            }
        });

        try {
            f = b.connect(host, port).sync(); // (5)
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static AvatarResponse sendRequest(AvatarRequest request){
        String requestStr = new Gson().toJson(request);
        f.channel().writeAndFlush(requestStr);
        f.channel().writeAndFlush("\r\n");
        AvatarFuture af = new AvatarFuture(request);
        try {
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
        }
        return af.get(request.getTimeout());
    }
}
